package com.javabasic.algorithm.leetcode;

import org.junit.Test;

/**
 * @Author xiongmin
 * @Description TODO
 * @Date 2019/10/22 12:54
 * @Version 1.0
 **/
public class StringToInteger {
    @Test
    public void test() {
        System.out.println(myAtoi("42"));
        System.out.println(myAtoi("   -42"));
        System.out.println(myAtoi("4193 with words"));
        System.out.println(myAtoi("words and 987"));
        System.out.println(myAtoi("-91283472332"));
        System.out.println(myAtoi("  -0012a42"));
        System.out.println(myAtoi("   +0 123"));
        System.out.println(myAtoi("2147483648"));

//        System.out.println(Integer.MAX_VALUE);
//        System.out.println(Integer.MAX_VALUE+1);
    }


    public int myAtoi(String str) {
        boolean flag = true; // 标记是否出现了第一个非空字符
        int ans = 0;
        char ch;
        boolean isNagative = false;
        for (int i = 0; i < str.length(); i++) {
            ch = str.charAt(i);
            if (ch == ' ' && flag) continue;
            if ((ch == '-' || ch == '+') && flag) {
                if (ch == '-') {
                    isNagative = true;
                }
                flag = false;
                continue;
            }

            if (ch >= '0' && ch <= '9') {
                if (ans*10L + ch-'0' > Integer.MAX_VALUE) {
                    if (isNagative) return -Integer.MAX_VALUE-1;
                    return Integer.MAX_VALUE;
                } else {
                    ans = ans*10 + ch-'0';
                }
            } else {
                if (isNagative) {
                    ans = -ans;
                }
                return ans;
            }

            flag = false;


        }
        if (isNagative) {
            ans = -ans;
        }
        return ans;
    }

}
